<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								订单
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar ref="scrollbarRef" @scroll="handleScroll"
					:style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="订单状态" prop="status" class="form-item-bg">
									<el-select @clear="selectClear('status')" v-model="formData.status"
										@change="(value:any)=>selectChange(value,'status')" multiple ref="status">
										<el-option v-for="(item, key) in statusOption" :key="key" :label="item?.label"
											:value="item?.value" :disabled="true">
											<!--  -->
											<el-tag style="border: 0;" :color="item?.color" round effect="dark">
												{{ item?.label }}
											</el-tag>
											<!--  -->
										</el-option>
										<!--  -->
										<template #tag>
											<el-tag style="border: 0;" v-show="statusOption[statusIndex]?.value"
												:color="statusOption[statusIndex]?.color" round effect="dark">
												{{ statusOption[statusIndex]?.label }}
											</el-tag>
										</template>
									</el-select>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="订单编号" prop="orderNumber" class="form-item-bg">
									<el-input type="text" v-model="formData.orderNumber" placeholder="自动生成无需填写" readonly
										clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<el-form-item label="客户" prop="customer">
							<el-select :readonly="route.query.id" @clear="selectClear('customer')"
								v-model="formData.customer" @change="(value:any)=>selectChange(value,'customer')"
								multiple ref="customer" clearable>
								<el-option v-for="item in customerOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div class="flex-align-center">
										<el-icon :color="customerOption[customerIndex]?.color">
											<component :is="customerOption[customerIndex]?.icon">
											</component>
										</el-icon>
										<!--  -->
										<el-text size="small"
											style="margin-left: 6px;">{{customerOption[customerIndex]?.label}}</el-text>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<div class="static-content-item">
							<div>基本信息</div>
						</div>
						<el-form-item label="合同附件" prop="contractAttachment">
							<el-input v-model="formData.contractAttachment" readonly clearable>
								<template #prefix>
									<el-upload v-model:file-list="formData.files" action="/api/oss/policy"
										:on-success="onSuccess" :headers="{'Authorization':cookie.get('token')}"
										:limit="1">
										<el-button v-if="!formData.contractAttachment" text :icon="UploadFilled">
											上传图片
										</el-button>
										<el-image v-else preview-teleported
											style="width: 30px; height: 30px;margin: 10px auto;"
											:src="formData.contractAttachment"
											:preview-src-list="[formData.contractAttachment]" />
									</el-upload>
								</template>
							</el-input>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="6">
								<el-form-item label="预计发货日期" prop="expectedDeliveryDate">
									<el-date-picker placeholder="请选择" style="width:100%;"
										v-model="formData.expectedDeliveryDate" type="date" />
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item label="异常状态" prop="abnormalState">
									<el-select @clear="selectClear('abnormalState')" v-model="formData.abnormalState"
										@change="(value:any)=>selectChange(value,'abnormalState')" multiple
										ref="abnormalState" clearable>
										<el-option v-for="(item, key) in abnormalStateOption" :key="key"
											:label="item?.label" :value="item?.value">
											<!--  -->
											<el-tag style="border: 0;" :color="item?.color" round effect="dark">
												{{ item?.label }}
											</el-tag>
											<!--  -->
										</el-option>
										<!--  -->
										<template #tag>
											<el-tag style="border: 0;"
												v-if="abnormalStateOption[abnormalStateIndex]?.value"
												:color="abnormalStateOption[abnormalStateIndex]?.color" round
												effect="dark">
												{{ abnormalStateOption[abnormalStateIndex]?.label }}
											</el-tag>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item label="下单日期" prop="orderDate">
									<el-date-picker placeholder="请选择" style="width:100%;" v-model="formData.orderDate"
										type="date" />
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item label="销售" prop="salesPerson">
									<el-input type="text" v-model="formData.salesPerson" readonly clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="备注" prop="remark">
							<el-input type="text" placeholder="请填写" v-model="formData.remark" clearable></el-input>
						</el-form-item>
						<!--  -->
						<div v-if="route.query.id">
							<div class="static-content-item">
								<div>应收&利润</div>
							</div>
							<el-row :gutter="16">
								<el-col :span="12">
									<el-form-item label="订单总额" prop="orderTotalAmount">
										<el-input type="number" v-model="formData.orderTotalAmount" readonly
											clearabl><template #suffix>
												<e-text>元</e-text>
											</template></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="退款金额" prop="refundAmount">
										<el-input type="number" v-model="formData.refundAmount" readonly
											clearable><template #suffix>
												<e-text>元</e-text>
											</template></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<!--  -->
							<el-row :gutter="16">
								<el-col :span="12">
									<el-form-item label="订单毛利率" prop="orderGrossMargin">
										<el-input type="text" :formatter="(value)=>value+'%'"
											v-model="formData.orderGrossMargin" readonly clearable><template #suffix>
												<e-text>%</e-text>
											</template></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="订单总利润" prop="totalProfit">
										<el-input type="number" v-model="formData.totalProfit" readonly
											clearable><template #suffix>
												<e-text>元</e-text>
											</template></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<!--  -->
							<el-row :gutter="16">
								<el-col :span="12">
									<el-form-item label="销售提成" prop="salesCommission">
										<el-input type="number" v-model="formData.salesCommission" readonly clearable>
											<template #suffix>
												<e-text>元</e-text>
											</template>
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="商品总成本" prop="totalCostOfGoods">
										<el-input type="number" v-model="formData.totalCostOfGoods" readonly clearable>
											<template #suffix>
												<e-text>元</e-text>
											</template>
										</el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
						<div v-if="route.query.id">
							<div class="static-content-item">
								<div>回款&开票</div>
							</div>
							<el-row :gutter="16">
								<el-col :span="6">
									<el-form-item label="待回款金额" prop="pendingCollectionAmount">
										<el-input type="text" v-model="formData.pendingCollectionAmount" readonly
											clearable></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="6">
									<el-form-item label="已回款金额" prop="receivedAmount">
										<el-input type="text" v-model="formData.receivedAmount" readonly
											clearable></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="6">
									<el-form-item label="待开票金额" prop="pendingInvoicingAmount">
										<el-input type="text" v-model="formData.pendingInvoicingAmount" readonly
											clearable></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="6">
									<el-form-item label="已开票金额" prop="invoicedAmount">
										<el-input type="text" v-model="formData.invoicedAmount" readonly
											clearable></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
						<el-form-item label="">
							<el-input type="text" ref="salesPerson" readonly clearable class="my1">
								<template #prefix>
									<div style="margin: 0;padding: 0;">
										<el-tabs v-model="activeName" @tab-click="handleClick" class="my">
											<el-tab-pane label="订单明细" name="order">
												<div class="flex-space-between"
													style="height: 48px;padding-left: 10px;">
													<el-text type="info" size="small">
														来自 <el-text type="primary" size="small">订单明细</el-text> 的数据
														共{{formData.tableData.length}}条
													</el-text>
													<el-text>
														<el-tooltip effect="light" :hide-after="50" content="创建"
															placement="top">
															<div class="my-a" @click="setTableData">
																<el-icon size="16px" color="#409EFF">
																	<CirclePlus />
																</el-icon>
															</div>
														</el-tooltip>
													</el-text>
												</div>
												<!--  -->
												<el-scrollbar style="width: calc(100vw - 48px - 32px);height: 300px;">
													<el-table @cell-dblclick="tableCellClick" v-loading="loading"
														:data="formData.tableData" :stripe="false" table-layout="auto"
														:default-sort="{}" border style="width: 100%;height: 300px;"
														class="my">
														<el-table-column width="76" fixed="left" prop="id"
															:sortable="false">
															<template #default="scope">
																<el-tooltip effect="light" :hide-after="50" content="复制"
																	placement="top">
																	<el-button style="padding: 0;" class="my"
																		@click="copyTableData(scope.$index)"
																		:icon="DocumentAdd"></el-button>
																</el-tooltip>
																<el-tooltip effect="light" :hide-after="50" content="删除"
																	placement="top">
																	<el-button style="padding: 0;" class="my"
																		@click="deleteTableData(scope.$index)"
																		:icon="Delete"></el-button>
																</el-tooltip>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="productId" label="下单产品*(可选)"
															:sortable="false">
															<template #default="scope">
																<div class="flex-align-center">
																	<el-icon :color="scope.row.product?.color">
																		<component :is="scope.row.product?.icon">
																		</component>
																	</el-icon>
																	<el-text size="small"
																		style="margin-left: 6px;">{{scope.row.product?.label}}</el-text>
																</div>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="currentInventory"
															label="当前库存数量" :sortable="false">
															<template #default="scope">
																<el-text>{{scope.row?.currentInventory ||scope.row?.products?.currentInventory}}</el-text>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="quantityOrdered"
															label="下单数量*(可选)" :sortable="false">
															<template #default="scope">
															</template>
														</el-table-column>
														<el-table-column width="140" prop="discountedPrice"
															label="折后单价*(可选)" :sortable="false">
															<template #default="scope">
															</template>
														</el-table-column>
														<el-table-column width="140" prop="subtotalAmount" label="金额小计"
															:sortable="false"></el-table-column>
														<el-table-column width="140" prop="costPrice" label="成本单价*(可选)"
															:sortable="false">
															<template #default="scope">
															</template>
														</el-table-column>
														<el-table-column width="140" prop="productCost" label="商品成本"
															:sortable="false"></el-table-column>
														<el-table-column width="140" prop="pendingShipmentQuantity"
															label="待申请发货数量" :sortable="false"></el-table-column>
														<el-table-column width="140" prop="shippedQuantity"
															label="已发货数量" :sortable="false"></el-table-column>
														<el-table-column width="140" prop="receivedQuantity"
															label="已签收数量" :sortable="false"></el-table-column>
														<el-table-column width="140" prop="returnedQuantity"
															label="已退货数量" :sortable="false"></el-table-column>
													</el-table>
												</el-scrollbar>
											</el-tab-pane>
										</el-tabs>
									</div>
								</template>
							</el-input>
						</el-form-item>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
			<!-- levitation  -->
			<levitation ref="levitationRef" :option="selectCell.option" :types="types" :st_type="selectCell.type"
				:params="levitationParams" :observerElement="scrollbarRef" :element="element" @change="levitationChange"
				@blur="levitationBlur" />
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { ref, onMounted, reactive, computed, Ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import { ArrowDown, UserFilled, Plus, UploadFilled, CirclePlus, Delete, DocumentAdd } from '@element-plus/icons-vue';
	import { ElLoading } from 'element-plus';
	import request from '../../../utils/request';
	import { ElMessage, FormInstance, UploadProps } from 'element-plus';
	import { colors, findIndexByLabel, isEmpty, mergeObjects, removeEmptyProperties, splitBy } from '../../../utils/index';
	import { formatDate } from '../../../utils/date';
	import { jwtDecode } from 'jwt-decode';
	import cookie from 'js-cookie';
	import { formatTableData, useSelect } from '../../../utils/mixins';
	import levitation from '../../../components/levitation-form/levitation-form.vue';
	import { getShipments } from '../../../api/shipmentAPI';
	import { divide, minus, times, } from '../../../utils/digit';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);
	const activeName = ref('order');
	//levitation start
	const element = ref(null);
	const levitationRef = ref(null);
	const scrollbarRef = ref(null);
	const types = ref('');
	const selectCell = ref({
		id: 0,
		property: '',
		type: '',
		option: []
	});
	const levitationParams = ref(null);
	//levitation end
	// 表单
	const formData = ref({
		status: [],
		orderStatusId: null,
		orderNumber: null,
		customer: [],
		customerId: null,
		contractAttachment: null,
		files: [],//文件
		expectedDeliveryDate: null,
		abnormalState: [],
		abnormalStateId: null,
		orderDate: null,
		salesPerson: null,
		remark: null,
		orderTotalAmount: null,
		refundAmount: null,
		orderGrossMargin: null,
		totalProfit: null,
		salesCommission: null,
		totalCostOfGoods: null,
		pendingCollectionAmount: null,
		receivedAmount: null,
		pendingInvoicingAmount: null,
		invoicedAmount: null,
		tableData: [],
	});
	//
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0
	});
	//

	const statusOption = ref([]);
	const customerOption = ref([]);
	const abnormalStateOption = ref([]);
	const productOption = ref([]);
	//
	//
	const rules = reactive({
		status: [{ required: true, message: '订单状态必选！', trigger: ['blur', 'change'] }],
		orderNumber: [],
		customer: [{ required: true, message: '客户必填！', trigger: ['blur', 'change'] }],
		contractAttachment: [],
		expectedDeliveryDate: [{ required: true, message: '预计发货日期必选！', trigger: ['blur', 'change'] }],
		abnormalState: [{ required: true, message: '异常状态必选！', trigger: ['blur', 'change'] }],
		orderDate: [{ required: true, message: '下单日期必选！', trigger: ['blur', 'change'] }],
		salesPerson: [{ required: true, message: '银行账号必选！', trigger: ['blur', 'change'] }],
		remark: [],
	});
	//
	onMounted(() => {
		// getCustomer();
		formData.value.status = [110];
		formData.value.orderStatusId = 110;
		statusIndex.value = 0;

	});
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getCustomer();
			//
			if (result) {
				getStatusList();
				getCustomerList();
				getStateList();
				getProductList();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		formData.value.tableData = [];
		//清空url参数
		router.push({ query: {} });
	}
	//设置一个
	const setTableData = () => {
		formData.value.tableData.push({
			id: +new Date(),
			productId: null,
			currentInventory: null,
			quantityOrdered: null,
			discountedPrice: null,
			subtotalAmount: null,
			costPrice: null,
			productCost: null,
			pendingShipmentQuantity: null,
			shippedQuantity: null,
			receivedQuantity: null,
			returnedQuantity: null,
			product: null
		});
	}
	//复制一个
	const copyTableData = (index : number) => {
		const item = { ...formData.value.tableData[index] };
		item.id = +new Date();
		formData.value.tableData.push(item);
	}
	//删除一个
	const deleteTableData = (index : number) => {
		formData.value.tableData.splice(index, 1);
	}
	//点击单元格回调
	const tableCellClick = (row : any, column : any, cell : HTMLTableCellElement, event : Event) => {
		console.log('row --->', row);
		types.value = '';
		//
		if (column.property === 'productId') {
			types.value = 'select-icon';
			selectCell.value.option = [...productOption.value];
		}
		if (column.property === 'quantityOrdered') {
			types.value = 'number';
		}
		if (column.property === 'discountedPrice') {
			types.value = 'number';
		}
		//
		element.value = cell;
		//
		selectCell.value.id = row.id;
		selectCell.value.property = column.property;
		//
		levitationParams.value = row[column.property];
		setTimeout(() => {
			levitationRef.value.getElementInfo();
		}, 1);
		//
	}

	//
	const getCustomer = async () => {
		if (!route.query.id) {
			const token = cookie.get('token');
			const decodedToken : {
				username : string
			} = jwtDecode(token);
			// console.log('decodedToken--->', decodedToken);
			//
			formData.value.salesPerson = decodedToken?.username;
			//
			return true;
		}
		const result = await request({
			url: '/login/selectSaleOrder',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getCustomer--->', result);
		formData.value = { ...result.data.t };
		//
		formData.value.tableData = [...result.data.t.orderDetail];
		//
		result.data.t.orderDetail.forEach((item : any, key : number) => {
			getProduct(item.products.productId, key, 'n');
		});
		return true;
	}
	//
	const selectClear = (type : string) => {
		formData.value[type] = [];
	}
	//ref
	const status = ref(null);
	const abnormalState = ref(null);
	const customer = ref(null);
	const salesPerson = ref(null);
	//
	const statusIndex = ref(-1);
	const abnormalStateIndex = ref(-1);
	const customerIndex = ref(-1);
	const productIndex = ref(-1);
	//
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'status', //哪一个下拉框，根据ref
			option: statusOption, //下拉列表选项
			indexVar: statusIndex, //当前选中项
			idVar: 'orderStatusId', //当前id值
			blurRef: status, //ref
		}, {
			type: 'customer',
			option: customerOption,
			indexVar: customerIndex,
			idVar: 'customerId',
			blurRef: customer,
		}, {
			type: 'abnormalState',
			option: abnormalStateOption,
			indexVar: abnormalStateIndex,
			idVar: 'abnormalStateId',
			blurRef: abnormalState,
		}, {
			type: 'abnormalState',
			option: abnormalStateOption,
			indexVar: abnormalStateIndex,
			idVar: 'abnormalStateId',
			blurRef: abnormalState,
		}];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//
	//获取客户信息
	const getCustomerList = async () => {
		// const loading = ElLoading.service({
		// 	lock: true,
		// 	text: '加载中...',
		// 	background: 'rgba(0, 0, 0, 0.5)',
		// });
		const result = await request({
			url: '/login/selectCustomerAll',
			params: pageData.value,
		});
		//
		console.log('getCustomerList --->', result);
		//
		pageData.value = mergeObjects(pageData.value, result.data.t);
		//
		customerOption.value = [];
		result.data.t.list.forEach((item : any, key : number) => {
			customerOption.value.push({
				label: `${item.customerName}（${item.customerRating}）${item.billingMethod}`,
				value: item.customerId,
				icon: UserFilled,
				color: '#82b51b'
			});
			if (formData.value.customerId === item.customerId) {
				formData.value.customer = [item.customerId];
				customerIndex.value = key;
			}
		});
		//
		// loading.close();
		return true;
	};
	//获取订单状态列表
	const getStatusList = async () => {
		const data = await getShipments('order_status');
		//
		console.log('getStatusList --->', data);
		//
		statusOption.value = [];
		data.forEach((item : any, key : number) => {
			statusOption.value.push(item);
			//
			if (formData.value.orderStatusId === item.value) {
				formData.value.status = [item.value];
				statusIndex.value = key;
			}
		});
	}
	//获取订单异常状态列表
	const getStateList = async () => {
		const result = await request({
			url: '/login/selectState',
		});
		//
		console.log('getStateList --->', result);
		//

		abnormalStateOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			abnormalStateOption.value.push({
				label: item?.state,
				color: JSON.parse(item.classColor).color,
				value: item?.id
			});
			if (formData.value.abnormalStateId === item.id) {
				formData.value.abnormalState = [item.id];
				abnormalStateIndex.value = key;
			}
		});
	}
	//获取所有产品
	const getProductList = async () => {
		const result = await request({
			url: '/login/selectProductAll',
		});
		//
		console.log('getProductList --->', result);
		//
		productOption.value = [];
		result.data.t.forEach((item : any) => {
			productOption.value.push({
				label: `${item?.productName}${item?.model} | 在库${item?.currentInventory}件`,
				value: item?.productId,
				icon: UploadFilled,
				color: '#5283ff'
			});
		})
	}
	//根据id获取产品
	const getProduct = async (id ?: string | number, key ?: number, type : string = 'y') => {
		if (!id) {
			return;
		}
		const result = await request({
			url: '/login/selectProduct',
			params: {
				id
			}
		});
		//
		console.log('getProduct --->', result);
		const item = formData.value.tableData[key];
		if (type === 'y') {
			formData.value.tableData[key] = { ...result.data.t };
		}
		formData.value.tableData[key].id = item.id;
		//
		formData.value.tableData[key].product = {
			label: `${result.data.t?.productName}${result.data.t?.model} | 在库${result.data.t?.currentInventory}件`,
			value: result.data.t?.productId,
			icon: UploadFilled,
			color: '#5283ff'
		}
		formData.value.tableData[key].discountedPrice = result.data.t.sellingPrice;
		//
		console.log('formData.value.tableData --->', formData.value.tableData);
	}

	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				//
				const data = { ...formData.value, orderDetail: [...formData.value.tableData] };
				delete data.status;
				delete data.customer;
				delete data.abnormalState;
				// console.log('submitForm ---> ', data);
				let type = '';
				if (!route.query.id) {
					type = '/saveSaleOrder';
				} else {
					type = '/updateSaleOrder';
				}
				//
				const result = await request({
					url: '/login' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//

				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});

					if (!route.query.id) {
						router.push({ query: { id: result.data.t.orderId } });
						route.query.id = result.data.t.orderId;
					}

					//

				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//
	//失去焦点
	const levitationBlur = () => {
		element.value = null;
	}
	//内容改变 *
	const levitationChange = (value : string | number) => {
		// console.log('value --->', value);
		formData.value.tableData.forEach((item : any, key : number) => {
			console.log('item.id --->', item.id, 'selectCell.value.id --->', selectCell.value.id);
			if (item.id === selectCell.value.id) {
				item[selectCell.value.property] = value;
				//下单产品
				if (selectCell.value.property === 'productId') {
					getProduct(value, key);
				}
				//下单数量
				if (selectCell.value.property === 'quantityOrdered') {
					computeAll();
				}
			}
		});
	}
	//滚动 *
	const handleScroll = (e : any) => {
		// console.log('handleScroll --->', e);
		if (element.value === null) return;
		levitationRef.value.getElementInfo();
	}
	//计算所有数据
	const computeAll = () => {
		const list = formData.value.tableData;
		formData.value.orderTotalAmount = 0;
		formData.value.totalCostOfGoods = 0;
		formData.value.refundAmount = 0;
		formData.value.totalProfit = 0;
		formData.value.orderGrossMargin = 0;
		formData.value.salesCommission = 0;
		formData.value.pendingCollectionAmount = 0;
		formData.value.receivedAmount = 0;
		formData.value.pendingInvoicingAmount = 0;
		formData.value.invoicedAmount = 0;
		//订单明细
		list.forEach((item : any, key : number) => {
			//下单数量不为空
			if (item.quantityOrdered) {
				//金额小计
				item.subtotalAmount = item.quantityOrdered * item.discountedPrice;
				//商品成本
				item.productCost = item.quantityOrdered * item.costPrice;
				//待申请发货数量
				item.pendingShipmentQuantity = item.quantityOrdered;
				//已发货数量
				item.shippedQuantity = 0;
				//已签收数量
				item.receivedQuantity = 0;
				//已退货数量
				item.returnedQuantity = 0;
				//
				//订单总额
				formData.value.orderTotalAmount += item.subtotalAmount;
				//商品总成本
				formData.value.totalCostOfGoods += item.productCost;
				//退款金额
				formData.value.refundAmount = 0;
				if ((list.length - 1) === key) {
					//订单总利润
					formData.value.totalProfit = formData.value.orderTotalAmount - formData.value.totalCostOfGoods;
					//订单毛利润
					formData.value.orderGrossMargin = ((formData.value.totalProfit / formData.value.orderTotalAmount) * 100).toFixed(2);
					//销售提成
					formData.value.salesCommission = (formData.value.orderTotalAmount * (3 / 100)).toFixed(2);
					//待回款金额
					formData.value.pendingCollectionAmount = formData.value.orderTotalAmount;
					//已回款金额
					formData.value.receivedAmount = 0;
					//待开票金额
					formData.value.pendingInvoicingAmount = 0;
					//已开票金额
					formData.value.invoicedAmount = 0;
				}
			} else {
				item.subtotalAmount = null;
				item.productCost = null;
				item.pendingShipmentQuantity = null;
				item.shippedQuantity = null;
				item.receivedQuantity = null;
				item.returnedQuantity = null;
				formData.value.orderTotalAmount = null;
				formData.value.totalCostOfGoods = null;
				formData.value.refundAmount = null;
				formData.value.totalProfit = null;
				formData.value.orderGrossMargin = null;
				formData.value.salesCommission = null;
				formData.value.pendingCollectionAmount = null;
				formData.value.receivedAmount = null;
				formData.value.pendingInvoicingAmount = null;
				formData.value.invoicedAmount = null;
			}
		});
	}
	//图片上传成功
	const onSuccess = (res : any) => {
		console.log('onSuccess --->', res);
		//
		formData.value.contractAttachment = res.t;
	}
	defineExpose({
		openDialog
	})
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
	.el-upload-list--text {
		display: none;
	}
	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>